package src.controller.mainInterface;

import javafx.animation.FadeTransition;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

public class habitcontroller implements Initializable {

    @FXML private StackPane studyCircle;
    @FXML private StackPane dailyCircle;
    @FXML private StackPane exerciseCircle;
    @FXML private StackPane habitCircle;
    @FXML private AnchorPane rootPane;

    private long pressStartTime;
    private static final long LONG_PRESS_DURATION = 1000; // 1秒长按
    private List<StackPane> floatingGoals = new ArrayList<>();

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // 添加空值检查
        if (studyCircle == null || dailyCircle == null || exerciseCircle == null || habitCircle == null) {
            System.err.println("❌ FXML 组件未正确注入，请检查 fx:id 设置");
            return;
        }

        setupClickHandlers();
        setupLongPressHandler();
        System.out.println("✅ HabitController 初始化完成");
    }

    private void setupClickHandlers() {
        // 为学习、日常、运动圆球设置点击事件
        studyCircle.setOnMouseClicked(this::handleCategoryClick);
        dailyCircle.setOnMouseClicked(this::handleCategoryClick);
        exerciseCircle.setOnMouseClicked(this::handleCategoryClick);
        // 习惯圆球不显示浮动目标
        habitCircle.setOnMouseClicked(event -> {}); // 空处理
    }

    private void setupLongPressHandler() {
        habitCircle.setOnMousePressed(this::handleMousePressed);
        habitCircle.setOnMouseReleased(this::handleMouseReleased);
    }

    private void handleMousePressed(MouseEvent event) {
        pressStartTime = System.currentTimeMillis();
    }

    private void handleMouseReleased(MouseEvent event) {
        long pressDuration = System.currentTimeMillis() - pressStartTime;
        if (pressDuration >= LONG_PRESS_DURATION) {
            navigateToPlanView();
        }
    }

    private void navigateToPlanView() {
        try {
            // 添加过渡动画
            FadeTransition fadeOut = new FadeTransition(Duration.millis(300), rootPane);
            fadeOut.setFromValue(1.0);
            fadeOut.setToValue(0.0);
            fadeOut.setOnFinished(e -> {
                try {
                    // 使用正确的路径 - 和plan.java中一样
                    Parent root = FXMLLoader.load(getClass().getResource("../../view/mainInterface/planview.fxml"));
                    Stage stage = (Stage) habitCircle.getScene().getWindow();
                    Scene scene = new Scene(root, 800, 600);

                    // 添加淡入动画
                    scene.getRoot().setOpacity(0);
                    stage.setScene(scene);

                    FadeTransition fadeIn = new FadeTransition(Duration.millis(300), scene.getRoot());
                    fadeIn.setFromValue(0.0);
                    fadeIn.setToValue(1.0);
                    fadeIn.play();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            });
            fadeOut.play();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void handleCategoryClick(MouseEvent event) {
        StackPane clickedCircle = (StackPane) event.getSource();
        showFloatingGoals(clickedCircle);
    }

    private void showFloatingGoals(StackPane parentCircle) {
        // 清除之前的目标
        clearFloatingGoals();

        // 获取父圆球的位置
        double centerX = parentCircle.getLayoutX();
        double centerY = parentCircle.getLayoutY();
        String category = getCategoryName(parentCircle);

        // 创建3个浮动目标圆球
        for (int i = 1; i <= 3; i++) {
            createFloatingGoal(centerX, centerY, i, category, 200 * i); // 延迟出现
        }
    }

    private String getCategoryName(StackPane circle) {
        if (circle == studyCircle) return "学习";
        if (circle == dailyCircle) return "日常";
        if (circle == exerciseCircle) return "运动";
        return "其他";
    }

    private void createFloatingGoal(double centerX, double centerY, int goalNumber, String category, double delay) {
        // 根据类别设置不同的位置偏移
        double offsetX = getOffsetX(category, goalNumber);
        double offsetY = getOffsetY(category, goalNumber);

        StackPane goalCircle = new StackPane();
        goalCircle.setPrefSize(getGoalSize(goalNumber), getGoalSize(goalNumber));
        goalCircle.setStyle("-fx-background-color: white; -fx-border-color: black; -fx-border-width: 1; -fx-background-radius: " + (getGoalSize(goalNumber)/2) + "; -fx-border-radius: " + (getGoalSize(goalNumber)/2) + ";");

        Label goalLabel = new Label("目标" + goalNumber);
        goalLabel.setStyle("-fx-font-size: " + getFontSize(goalNumber) + "px; -fx-font-weight: bold;");
        goalCircle.getChildren().add(goalLabel);

        // 设置位置（根据habitsView.fxml中的布局）
        goalCircle.setLayoutX(centerX + offsetX);
        goalCircle.setLayoutY(centerY + offsetY);
        goalCircle.setOpacity(0);

        // 添加到场景和列表
        rootPane.getChildren().add(goalCircle);
        floatingGoals.add(goalCircle);

        // 创建淡入动画
        FadeTransition fadeIn = new FadeTransition(Duration.millis(500), goalCircle);
        fadeIn.setDelay(Duration.millis(delay));
        fadeIn.setFromValue(0.0);
        fadeIn.setToValue(1.0);
        fadeIn.play();
    }

    private double getGoalSize(int goalNumber) {
        switch (goalNumber) {
            case 1: return 30.0;  // 半径15
            case 2: return 45.0;  // 半径22.5
            case 3: return 55.0;  // 半径27.5
            default: return 30.0;
        }
    }

    private double getFontSize(int goalNumber) {
        switch (goalNumber) {
            case 1: return 8.0;
            case 2: return 10.0;
            case 3: return 12.0;
            default: return 8.0;
        }
    }

    private double getOffsetX(String category, int goalNumber) {
        // 根据habitsView.fxml中的实际布局计算偏移量
        switch (category) {
            case "学习":
                switch (goalNumber) {
                    case 1: return -52.5; // 307.75 - 360.25
                    case 2: return -91.5; // 268.75 - 360.25
                    case 3: return -53.35; // 306.90 - 360.25
                }
            case "日常":
                switch (goalNumber) {
                    case 1: return -49.25; // 89.0 - 138.25
                    case 2: return -91.0; // 47.25 - 138.25
                    case 3: return -56.25; // 82.0 - 138.25
                }
            case "运动":
                switch (goalNumber) {
                    case 1: return -52.5; // 560 - 612.5
                    case 2: return -91.5; // 521 - 612.5
                    case 3: return -54.35; // 558.15 - 612.5
                }
            default: return -50;
        }
    }

    private double getOffsetY(String category, int goalNumber) {
        // 根据habitsView.fxml中的实际布局计算偏移量
        switch (category) {
            case "学习":
                switch (goalNumber) {
                    case 1: return 62.5; // 122.8333 - 60.3333
                    case 2: return 11.5; // 71.8333 - 60.3333
                    case 3: return -38.7333; // 21.60 - 60.3333
                }
            case "日常":
                switch (goalNumber) {
                    case 1: return 70.75; // 484.0 - 413.25
                    case 2: return 17.0; // 430.25 - 413.25
                    case 3: return -35.75; // 377.5 - 413.25
                }
            case "运动":
                switch (goalNumber) {
                    case 1: return 62.5; // 462.5 - 400.0
                    case 2: return 11.5; // 411.5 - 400.0
                    case 3: return -38.7333; // 361.2667 - 400.0
                }
            default: return 0;
        }
    }

    private void clearFloatingGoals() {
        for (StackPane goal : floatingGoals) {
            rootPane.getChildren().remove(goal);
        }
        floatingGoals.clear();
    }
}